import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [networkStatus, setNetworkStatus] = useState(navigator.onLine ? 'online' : 'offline');
  const navigate = useNavigate();

  // 监听网络状态变化
  useEffect(() => {
    const handleOnline = () => {
      setNetworkStatus('online');
    };
    
    const handleOffline = () => {
      setNetworkStatus('offline');
    };
    
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    
    // 如果用户已登录，直接跳转到文档页面
    if (localStorage.getItem('token')) {
      navigate('/docs');
    }
    
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, [navigate]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    
    if (loading) {
      return;
    }
    
    setLoading(true);
    
    try {
      // 清除旧数据
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      
      // 发送登录请求
      const response = await axios.post('/api/auth/login', { email, password });
      
      // 保存认证信息
      localStorage.setItem('token', response.data.token);
      
      if (response.data.user) {
        localStorage.setItem('userInfo', JSON.stringify({
          id: response.data.user.id,
          username: response.data.user.username,
          email: response.data.user.email,
          avatar: response.data.user.avatar
        }));
      }
      
      // 使用直接的页面跳转
      window.location.href = '/docs';
      
    } catch (error) {
      setLoading(false);
      console.error('登录失败:', error);
      
      if (error.response) {
        setError(error.response.data?.message || '登录失败，请检查邮箱和密码');
      } else if (error.request) {
        setError('服务器未响应，请检查您的网络连接');
      } else {
        setError('登录请求发送失败');
      }
    }
  };

  return (
    <div className="auth-container" style={{
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      minHeight: '500px',
      padding: '50px 30px'
    }}>
      <h2>登录</h2>
      
      {error && (
        <div className="message error">
          {error}
        </div>
      )}
      
      {networkStatus === 'offline' && (
        <div className="message error">
          您当前处于离线状态，请检查网络连接
        </div>
      )}
      
      <form onSubmit={handleSubmit}>
        <input
          type="email"
          placeholder="邮箱"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          disabled={loading}
          required
        />
        <input
          type="password"
          placeholder="密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          disabled={loading}
          required
        />
        <button type="submit" disabled={loading}>
          {loading ? '登录中...' : '登录'}
        </button>
      </form>
      <div className="auth-links">
        <p>没有账号？<Link to="/register">立即注册</Link></p>
        <p><Link to="/forgot-password">忘记密码？</Link></p>
      </div>
    </div>
  );
}